package com.dimples.dd.system.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.system.api.logger.dto.OperateLogCreateReqDTO;
import com.dimples.dd.system.convert.OperateLogConvert;
import com.dimples.dd.system.mapper.SystemOperateLogMapper;
import com.dimples.dd.system.model.bo.SystemOperateLogBO;
import com.dimples.dd.system.model.entity.SystemOperateLogDO;
import com.dimples.dd.system.model.query.OperateLogPageQuery;
import com.dimples.dd.system.model.vo.OperateLogPageVO;
import com.dimples.dd.system.service.SystemOperateLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import static com.dimples.dd.system.model.entity.SystemOperateLogDO.REQUEST_PARAMS_MAX_LENGTH;
import static com.dimples.dd.system.model.entity.SystemOperateLogDO.RESULT_MSG_MAX_LENGTH;

@Service
@RequiredArgsConstructor
public class SystemOperateLogServiceImpl extends ServiceImpl<SystemOperateLogMapper, SystemOperateLogDO> implements SystemOperateLogService{
    
    private final OperateLogConvert operateLogConvert;

    @Override
    public void createOperateLog(OperateLogCreateReqDTO operateLogCreateReqDTO) {
        SystemOperateLogDO entity = this.operateLogConvert.vo2Entity(operateLogCreateReqDTO);
        entity.setBeginTime(DateUtil.parseLocalDateTime(operateLogCreateReqDTO.getBeginTime(), DatePattern.NORM_DATETIME_MS_PATTERN));
        entity.setEndTime(DateUtil.parseLocalDateTime(operateLogCreateReqDTO.getEndTime(), DatePattern.NORM_DATETIME_MS_PATTERN));

        entity.setRequestParams(StrUtil.maxLength(entity.getRequestParams(), REQUEST_PARAMS_MAX_LENGTH));
        entity.setResultMsg(StrUtil.maxLength(entity.getResultMsg(), RESULT_MSG_MAX_LENGTH));
        /*if (TenantContextHolder.getTenantId() != null) {
            this.baseMapper.insert(entity);
        } else {
            // 极端情况下，上下文中没有租户时，此时忽略租户上下文，避免插入失败！
            TenantUtils.executeIgnore(() -> this.baseMapper.insert(entity));
        }*/
        // todo: 需要接入多租户操作
        this.baseMapper.insert(entity);
    }

    @Override
    public PageResult<OperateLogPageVO> selectOperateLogPage(OperateLogPageQuery pageQuery) {
        PageResult<SystemOperateLogBO> pageResult = this.baseMapper.selectOperateLogPage(pageQuery);
        return this.operateLogConvert.boPage2VO(pageResult);
    }
}
